package org.dru.clay.rhino.feature;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collection;

/**
 * Feature
 * User: joakimd
 * Date: 2013-07-17
 * Time: 09:58
 */
public abstract class Feature {
    public abstract void init(final Context context, final ScriptableObject scope) throws Exception;

    protected static void loadFeatureScript(final Context context, final ScriptableObject scope,
                                            final Class<?> featureClass, final String resource) throws Exception {
        final InputStream in = featureClass.getResourceAsStream(resource);
        if (in != null) {
            try {
                final InputStreamReader reader = new InputStreamReader(in);
                try {
                    context.evaluateReader(scope, reader, resource, 1, null);
                } finally {
                    reader.close();
                }
            } finally {
                in.close();
            }
        } else {
            throw new IOException("resource not found: " + resource);
        }
    }

    protected static void loadFeatureScript(final Context context, final ScriptableObject scope,
                                            final Class<?> featureClass) throws Exception {
        loadFeatureScript(context, scope, featureClass, featureClass.getSimpleName() + ".js");
    }

    protected static Scriptable getObject(final Scriptable obj, final String name) {
        return (Scriptable) ScriptableObject.getProperty(obj, name);
    }

    protected static String getString(final Scriptable obj, final String name) {
        return Context.toString(ScriptableObject.getProperty(obj, name));
    }

    protected static String[] toStringArray(final Object[] args) {
        final String[] result = new String[args.length];
        for (int index = 0; index < args.length; index++) {
            result[index] = Context.toString(args[index]);
        }
        return result;
    }

    protected static Collection<String> toStringCollection(final Object[] args) {
        return Arrays.asList(toStringArray(args));
    }
}
